import { login, logout, getOnlineUserCount } from '@/api/auth'

const state = {
  user: null,
  onlineUsers: 0
}

const mutations = {
  SET_USER: (state, user) => {
    console.log('SET_USER mutation called with:', user)
    state.user = user
  },
  SET_ONLINE_USERS: (state, count) => {
    console.log('SET_ONLINE_USERS mutation called with:', count)
    state.onlineUsers = count
  }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then(response => {
          console.log('Login response:', response)
          const { user, onlineUsers } = response
          commit('SET_USER', user)
          commit('SET_ONLINE_USERS', onlineUsers)
          resolve(response)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 用户登出
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      if (!state.user || !state.user.id) {
        console.error('No user ID found for logout')
        commit('SET_USER', null)
        commit('SET_ONLINE_USERS', 0)
        localStorage.removeItem('token')
        resolve()
        return
      }

      console.log('Logging out user:', state.user.id)
      logout(state.user.id)
        .then((response) => {
          console.log('Logout successful, response:', response)
          commit('SET_USER', null)
          commit('SET_ONLINE_USERS', 0)
          localStorage.removeItem('token')
          resolve(response)
        })
        .catch(error => {
          console.error('Logout failed:', error)
          commit('SET_USER', null)
          commit('SET_ONLINE_USERS', 0)
          localStorage.removeItem('token')
          reject(error)
        })
    })
  },

  // 获取在线用户数
  getOnlineUsers({ commit }) {
    return new Promise((resolve, reject) => {
      getOnlineUserCount()
        .then(response => {
          console.log('getOnlineUserCount response:', response)
          commit('SET_ONLINE_USERS', response)
          resolve(response)
        })
        .catch(error => {
          console.error('Failed to get online users count:', error)
          reject(error)
        })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 